<template>
  <div class="login-view">
    <div class="login-mask">
      <a-form
        ref="formRef"
        :model="form"
        :label-col-props="{ span: 0 }"
        :wrapper-col-props="{ span: 24 }"
      >
        <div class="title">登录</div>
        <a-form-item
          field="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
          ><a-input
            v-model="form.username"
            placeholder="请输入用户名"
            allow-clear
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
          field="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password
            v-model="form.password"
            placeholder="请输入密码"
            allow-clear
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" long @click="handleLogin">登录</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Message } from "@arco-design/web-vue";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { loginApi } from "@/api";
import { userStoreModel } from "@/stores/user/index.ts";

import { MsgEnum } from "@/enum/msg";

const router = useRouter();
const route = useRoute();
const formRef = ref();
const userStore = userStoreModel();

const form = reactive({
  username: "",
  password: "",
});

const handleLogin = async () => {
  const val = await formRef.value.validate();
  if (val) return;
  try {
    const {
      data: { token },
    } = await loginApi(form);

    userStore.saveUserInfo(token);
    Message.success("登录成功");

    userStore.loadUserinfo();
    const redirect = route.query.redirect;

    if (redirect) {
      router.push(redirect as string);
      return;
    }
    router.push({ name: "Home" });
  } catch (err) {
    console.log(err);

    Message.error(MsgEnum.fail);
  }
};
</script>
<style scoped lang="less">
.login-view {
  background: url("@/assets/login_bg.png") 50% / cover no-repeat;
  position: relative;
  height: 100vh;

  .login-mask {
    width: 400px;
    height: 100vh;
    background-color: var(--color_bg);
    position: absolute;
    top: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;

    .arco-form {
      padding: 40px;
    }

    .title {
      font-size: 26px;
      font-weight: 600;
      text-align: center;
      color: @primary-6;
      margin-bottom: 10px;
      font-family: kuaikan;
    }
  }
}
</style>
